package com.zhang.generic;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestGeneric {

    public static void main(String[] args) {
        TestGeneric testGeneric = new TestGeneric();

        IAnimalService animalService = new AnimalServiceImpl();
        DogEntity dogEntity = new DogEntity();
        dogEntity.setDogName("xiaohuang");
        animalService.play(dogEntity);

        IAnimalService animalService1 = new AnimalService2Impl();
        animalService1.play(dogEntity);

        List<Object> strs = new ArrayList<Object>();
        List<String> strs2 = new ArrayList<String>();
        testGeneric.testObject(strs);
        testGeneric.testObject2(strs2);
        testGeneric.testObject3(new DogEntity());

        //若不指定泛型，则默认的类型为Object
        List list = new ArrayList();
        System.out.println(testGeneric.testObj4(1));
        System.out.println(testGeneric.testObj4("aa"));
        System.out.println(testGeneric.testObj4(true));
        System.out.println(testGeneric.testObj4(0.88));
        System.out.println(testGeneric.testObj4(new DogEntity()));

        testGeneric.testObj5(1);
    }

    public void testObject(List<Object> list) {
        for (Object o : list) {
            System.out.println(o);
        }
    }

    public void testObject2(List<?> list) {

        for (Object o : list) {
            System.out.println(o);
        }
    }

    public void testObject3(Object object) {
        //未使用泛型之前需要使用object对象，然后强转
        DogEntity object1 = (DogEntity) object;
    }

    public <E> void testObj5(E e) {
        System.out.println(e);
    }

    public <E> E testObj4(E e) {
        return e;
    }

    public void testObj5(List<DogEntity> dogEntity) {
        dogEntity.add(new DogEntity());
    }

    public void show(List<Object> list) {
        list.add("d");
        list.add(33);
    }


    //泛型方法
    public <Y> Y show(Y y) {
        return y;
    }


    //通配符?
    public void test5() {

        List<Object> list1 = new ArrayList<Object>();
        List<String> list2 = null;

        //不成立，list1与list2为并列关系，不存在父子关系
//        list1=list2;

        //list3相当于是list2 list3的父类
        List<?> list3 = null;

        list1.add("AA");
        list1.add("BB");
        list1.add("CC");
        list3 = list1;
        list3 = list2;

        print(list1);
        print(list2);

        //通配符的只能项其内部add null,对于？通配符，不允许写入只允许读，读取的数据类型为Object类型
//        list3.add("");
//        list3.add(new Object());
        list3.add(null);
        Object o = list3.get(0);
        System.out.println(o);
    }

    public void print(List<?> list) {
        Iterator<?> iterator = list.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }
    }

    //有限制条件的通配符


}
